<template>
  <div class="app-container">
    {{ routeInfo }}
    <el-row :gutter="5">
      <!-- 用户管理模块 -->
      <el-col :span="7" :xs="24" :xl="24">
        <el-container style="box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); height: 100%; margin-bottom:0; padding:0; background: whitesmoke;">
          <center><h5>用户</h5></center>
          <el-header>
            <el-button-group>
              <el-input v-model="userQueryKey" type="text" style="width:70%" />
              <el-button class="el-icon-search" title="搜索用户" @click="searchUser" />
            </el-button-group><br>
            <el-button-group>
              <el-tooltip content="新增用户" placement="bottom">
                <el-button size="small" class="el-icon-circle-plus" @click="handlerCreateUser" />
              </el-tooltip>
              <el-tooltip content="修改用户" placement="bottom">
                <el-button size="small" class="el-icon-edit" @click="handlerUpdateUser" />
              </el-tooltip>
              <el-tooltip content="删除用户" placement="bottom">
                <el-button size="small" class="el-icon-remove" @click="handlerDeleteUser" />
              </el-tooltip>
              <el-tooltip content="分配所属角色" placement="bottom">
                <el-button size="small" class="el-icon-share" @click="handlerUR" />
              </el-tooltip>
            </el-button-group>
          </el-header>
          <el-main>
            <hr>
            <el-radio-group v-model="chosenuser" style="width:90%">
              <div v-for="user in allusers" :key="user.userId">
                <el-radio :id="user.userId" :label="user.userId" border size="small" style="width:100%" @change="chooseUser(user)">{{ user.userRealname }}</el-radio><br>
              </div>
            </el-radio-group>
          </el-main>
        </el-container>
      </el-col>
      <!-- 角色管理模块 -->
      <el-col :span="7" :xs="24" :xl="24">
        <el-container style="box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); height: 100%; margin-bottom:0; padding:0;  background: honeydew">
          <center><h5>角色</h5></center>
          <el-header height="20px">
            <el-button-group>
              <el-tooltip content="新增角色" placement="bottom">
                <el-button size="small" class="el-icon-circle-plus" @click="handlerCreateRole" />
              </el-tooltip>
              <el-tooltip content="修改角色" placement="bottom">
                <el-button size="small" class="el-icon-edit" @click="handlerUpdateRole" />
              </el-tooltip>
              <el-tooltip content="删除角色" placement="bottom">
                <el-button size="small" class="el-icon-remove" @click="handlerDeleteRole" />
              </el-tooltip>
              <el-tooltip content="分配角色权限" placement="bottom">
                <el-button size="small" class="el-icon-share" @click="handlerRA" />
              </el-tooltip>
            </el-button-group>
          </el-header>
          <el-main>
            <hr>
            <el-checkbox-group v-model="chosenRole" style="width:90%" @change="chooseRole">
              <div v-for="role in allRoles" :key="role.roleId">
                <el-checkbox :id="role.roleId" :label="role.roleId" border size="small" style="width:100%">{{ role.roleName }}</el-checkbox><br>
              </div>
            </el-checkbox-group>
          </el-main>
        </el-container>
      </el-col>
      <!-- 菜单管理模块 -->
      <el-col :span="10" :xs="24" :xl="24">
        <el-container style="box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)">
          <center><h5>菜单</h5></center>
          <el-header height="0px">
            <hr>
          </el-header>
          <el-main>
            <div id="userDiv" class="form-group alert alert-info">
              <el-tree
                ref="menuTree"
                :data="routeInfo"
                :props="defaultMenuProps"
                show-checkbox
                class="filter-tree"
                default-expand-all
                node-key="menuId"
                check-on-click-node
              >
                <div slot-scope="{ node, data }" class="custom-tree-node">
                  <span>
                    <el-tag v-if="data.menuType === '1'" size="mini" type="info">{{ node.label }}</el-tag>
                    <el-tag v-if="data.menuType === '2'" size="mini" type="success">{{ node.label }}</el-tag>
                  </span>
                    <!-- <span>
                      <el-tag v-if="data.menuType === '1'" size="mini" effect="dark">菜单</el-tag>
                      <el-tag v-if="data.menuType === '2'" size="mini" type="success" effect="dark">页面</el-tag>
                      <el-tag v-if="data.menuType === '3'" size="mini" type="info" effect="dark">页面控件</el-tag>
                    </span> -->
                    <span>
                    <el-checkbox-group v-if="data.menuType === '2'" v-model="pageAuth" size="mini">
                      <el-checkbox-button :label="data.controllerCode+'_query'">查询</el-checkbox-button>
                      <el-checkbox-button :label="data.controllerCode+'_modify'">修改</el-checkbox-button>
                      <el-checkbox-button :label="data.controllerCode+'_export'">导出</el-checkbox-button>
                    </el-checkbox-group>
                  </span>
                </div>
              </el-tree>
            </div>
          </el-main>
        </el-container>
      </el-col>
    </el-row>

    <el-dialog v-el-drag-dialog :title="titleMap[dialogStatus]" :visible.sync="userDialogVisible" center @dragDialog="handleDrag">
      <el-form ref="userForm" :model="tempuser" :rules="userFormRules" :disabled="dialogStatus === 'viewUser'" label-position="left" label-width="70px">
        <el-form-item label="userId" prop="userId">
          <el-input v-model="tempuser.userId" type="text" placeholder="编号不可编辑，系统自动生成" maxlength="10" readonly />
        </el-form-item>
        <el-form-item label="账户" prop="userName">
          <el-input v-model="tempuser.userName" type="text" placeholder="账户" maxlength="10" />
        </el-form-item>
        <el-form-item label="姓名" prop="userRealname">
          <el-input v-model="tempuser.userRealname" type="text" placeholder="姓名" maxlength="10" />
        </el-form-item>
        <el-form-item label="密码" prop="userPassword">
          <el-input v-if="dialogStatus == 'createUser'" v-model="tempuser.userPassword" type="text" placeholder="默认为123456" maxlength="20" disabled="" />
          <el-checkbox v-if="dialogStatus == 'updateUser'" v-model="tempuser.resetPassword" label="重置为123456" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmCreateUser">确 定</el-button>
        <el-button @click="userDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog v-el-drag-dialog :title="titleMap[dialogStatus]" :visible.sync="roleDialogVisible" center @dragDialog="handleDrag">
      <el-form ref="roleForm" :model="temprole" :rules="roleFormRules" :disabled="dialogStatus === 'viewRole'" label-position="left" label-width="70px">
        <el-form-item label="roleId" prop="roleId">
          <el-input v-model="temprole.roleId" type="text" placeholder="编号不可编辑，系统自动生成" maxlength="10" readonly />
        </el-form-item>
        <el-form-item label="角色code" prop="roleCode">
          <el-input v-model="temprole.roleCode" type="text" placeholder="角色Code" maxlength="10" :readonly="dialogStatus === 'updateRole'" />
        </el-form-item>
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="temprole.roleName" type="text" placeholder="角色名" maxlength="10" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmUpsertRole">确 定</el-button>
        <el-button @click="roleDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { queryUser, modifyUser, deleteUser, queryRole, deleteRole, queryAllMenu, confirmRA, confirmUR, upsertRole } from '@/api/userManage'
import { Message } from 'element-ui'

export default {
  directives: { elDragDialog }, // dialog拖拽
  data() {
    return {
      allusers: [], // 查询出的用户
      chosenuser: '', // 选中的用户ID
      userQueryKey: '', // 用户查询关键字
      userQueryCond: {}, // 用户查询条件
      tempuser: {}, // 编辑修改的用户
      userDialogVisible: false, // 用户编辑数据框可见状态
      userFormRules: {
        userName: [
          { required: true, message: '必填数据', trigger: 'change' },
          { max: 10, message: '超过最大长度', trigger: 'blur' }
        ],
        userRealname: [
          { required: true, message: '必填数据', trigger: 'change' },
          { max: 10, message: '超过最大长度', trigger: 'blur' }
        ]
      },
      allRoles: [], // 所有角色
      chosenRole: [], // 选中的角色
      roleDialogVisible: false, // 角色编辑框可见状态
      temprole: {}, // 编辑的角色
      roleFormRules: {
        roleCode: [
          { required: true, message: '必填数据', trigger: 'change' },
          { max: 10, message: '超过最大长度', trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: '必填数据', trigger: 'change' },
          { max: 10, message: '超过最大长度', trigger: 'blur' }
        ]
      },
      dialogStatus: '',
      titleMap: {// 数据框标题
        updateUser: '修改用户',
        createUser: '新增用户',
        viewRole: '查看角色',
        updateRole: '修改角色',
        createRole: '新增角色'
      },
      routeInfo: [], // 系统菜单
      chosenMenu: [], // 选中的菜单
      chosenFolder: [], // 半选中的目录菜单
      pageAuth: [], // 选中的按钮权限
      defaultMenuProps: {
        children: 'subMenus',
        label: 'menuName'
      }
    }
  },
  created() {
    this.searchUser() // 默认加载用户
    this.searchRole() // 默认加载角色
    this.showRouters() // 默认加载菜单
  },
  methods: {
    searchUser() {
      this.userQueryCond.userName = this.userQueryKey
      queryUser(this.userQueryCond).then(response => {
        this.allusers = response
      })
    },
    searchRole() {
      queryRole().then(response => {
        this.allRoles = response
        this.chooseRole(this.chosenRole)
      })
    },
    showRouters() {
      queryAllMenu().then(data => {
        this.routeInfo = data
      })
    },
    chooseUser(user) {
      this.chosenuser = user.userId // 这个只是选中页面上的单选框
      this.tempuser = user

      this.chosenRole = []
      if (user.userRoles) {
        var roles = user.userRoles.split('|')
        for (var i = 0; i < roles.length; i++) {
          if (roles[i]) {
            this.chosenRole.push(roles[i])
          }
        }
      }
      this.chooseRole(this.chosenRole)
    },
    handlerCreateUser() { // 点击创建用户按钮
      this.tempuser = {}
      this.dialogStatus = 'createUser'
      this.userDialogVisible = true
    },
    confirmCreateUser() {
      this.$refs['userForm'].validate((valid) => {
        if (valid) {
          this.$confirm('确认修改用户数据？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }).then(() => {
            modifyUser(this.tempuser).then(response => {
              if (response.code && response.code === '1') {
                this.userDialogVisible = false
                Message.success(response.msg)
                this.searchUser()
              } else {
                Message.error(response.msg)
              }
            })
          }).catch(() => {
            console.info('已取消')
          })
        }
      })
    },
    handlerUpdateUser() { // 点击修改用户按钮
      if (!this.chosenuser) {
        Message({
          message: '请选择用户',
          center: true
        })
      } else {
        this.dialogStatus = 'updateUser'
        this.userDialogVisible = true
      }
    },
    handlerDeleteUser() { // 点击删除用户按钮
      if (!this.chosenuser) {
        Message({
          message: '请选择用户',
          center: true,
          type: 'error'
        })
      } else {
        this.$confirm('删除用户数据后，将不可以恢复，确认删除用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          deleteUser(this.chosenuser).then(response => {
            Message.success(response)
            this.searchUser()
          })
        }).catch(() => {
          console.info('已取消')
        })
      }
    },
    handlerUR() { // 点击分配用户角色
      this.$confirm('调整用户角色后，需等用户重新登录时生效', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.chosenMenu = [...this.$refs.menuTree.getCheckedNodes()]
        var rolesInfo = ''
        this.chosenRole.forEach(roleId => {
          rolesInfo += roleId + '|'
        })
        confirmUR({ 'userId': this.chosenuser, 'roles': rolesInfo }).then(() => {
          Message.success('已分配用户角色，用户重新登录后生效')
          this.searchUser()
        })
      })
    },
    handlerCreateRole() { // 点击创建角色按钮
      this.temprole = {}
      this.dialogStatus = 'createRole'
      this.roleDialogVisible = true
    },
    handlerUpdateRole() { // 点击查看角色按钮
      if (!this.chosenRole || this.chosenRole.length !== 1) {
        Message({
          message: '请选择一个角色',
          center: true,
          type: 'error'
        })
      } else {
        for (var key in this.allRoles) {
          if (this.allRoles[key].roleId === this.chosenRole[0]) {
            this.temprole = this.allRoles[key]
            break
          }
        }
        this.dialogStatus = 'updateRole'
        this.roleDialogVisible = true
      }
    },
    handlerDeleteRole() { // 点击删除角色按钮
      if (!this.chosenRole || this.chosenRole.length <= 0) {
        Message({
          message: '请选择角色',
          center: true,
          type: 'error'
        })
      } else {
        this.$confirm('删除角色后，将同时删除角色相关联数据，并且不可恢复，确认删除用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          var roles = ''
          for (var key in this.chosenRole) {
            roles += this.chosenRole[key] + '|'
          }
          deleteRole(roles).then(response => {
            Message.success(response)
            this.searchUser()
            this.searchRole()
            this.$refs.menuTree.setCheckedKeys([])
          })
        }).catch(() => {
          console.info('已取消')
        })
      }
    },
    chooseRole(roles) { // 选中角色
      var selectedMenusIds = []
      this.pageAuth = []
      this.chosenRole.forEach(roleId => {
        this.allRoles.forEach(role => {
          if (role.roleId === roleId) {
            role.menuIds.split('|').forEach(menuId => {
              if (menuId) {
                selectedMenusIds.push(menuId)
              }
            })
            role.pageAuth.split('|').forEach(pa => {
              if (pa) {
                this.pageAuth.push(pa)
              }
            })
          }
        })
      })
      this.$refs.menuTree.setCheckedKeys(selectedMenusIds)
    },
    handlerRA() { // 点击分配角色菜单
      if (!this.chosenRole || this.chosenRole.length !== 1) {
        Message({
          message: '请选择一个角色',
          center: true,
          type: 'error'
        })
      } else {
        this.$confirm('重新分配角色权限后，将在用户下次登录时生效', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          this.chosenMenu = [...this.$refs.menuTree.getCheckedNodes()]
          this.chosenFolder = [...this.$refs.menuTree.getHalfCheckedNodes()]
          var menusInfo = '' // 选中的节点
          this.chosenMenu.forEach(node => {
            menusInfo += (node.menuId ? node.menuId : ' ') + ',' + (node.menuType ? node.menuType : ' ') +
             ',' + (node.controllerCode ? node.controllerCode : ' ') + '|'
          })
          var folderInfo = '' // 半选中的目录
          this.chosenFolder.forEach(node => {
            folderInfo += (node.menuId ? node.menuId : ' ') + ',' + (node.menuType ? node.menuType : ' ') +
             ',' + (node.controllerCode ? node.controllerCode : ' ') + '|'
          })
          var paInfo = '|'
          this.pageAuth.forEach(pa => {
            paInfo += pa + '|'
          })
          confirmRA({ 'role': this.chosenRole[0], 'menusInfo': menusInfo, 'folderInfo': folderInfo, 'pageAuth': paInfo }).then(() => {
            Message.success('已分配角色权限，用户重新登录后生效')
            this.searchRole()
          })
        })
      }
    },
    confirmUpsertRole() {
      this.$refs['roleForm'].validate((valid) => {
        if (valid) {
          this.$confirm('确认修改角色数据？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }).then(() => {
            upsertRole(this.temprole).then(response => {
              Message.info(response)
              this.searchRole()
              this.roleDialogVisible = false
            })
          }).catch(() => {
            console.info('已取消')
          })
        }
      })
    },
    handleDrag() { // dialog拖拽事件
    },
    handleCheckMenuChange(data, checked, indeterminate) {
      // console.log(data, checked, indeterminate)
    }
  }
}
</script>

<style>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
.custom-tree-node .el-checkbox{
  margin-right:0px
}
.custom-tree-node .el-checkbox__label{
  padding-left:0px
}
.custom-tree-node .el-checkbox-group{
  width:200px;
  display: flex;
  align-items:center;
  right: 0;
  /* position: fixed; */
}
.custom-tree-node .el-checkbox-button__inner{
  width: 50px;
}
</style>
